/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sg.edu.nus.iss.pacman.dao;

import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

import sg.edu.nus.iss.pacman.util.IOUtils;

/**
 * An implementation class for UserProfile DAO with RMS.
 * @author fredy
 */
public class RmsUserProfileDao implements UserProfileDao
{
    private RecordStore rs;
    
    /**
     * Creates a new instance of RmsUserProfileDao.
     */
    public RmsUserProfileDao()
    {
        try
        {
            rs = RecordStore.openRecordStore("PacManUserProfile", true);
        }
        catch (RecordStoreException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }

    /**
     * Finds the UserProfile by id.
     * @param name user name
     * @return the UserProfile or null if it doesn't exist
     */
    public UserProfile findUserProfile(String name)
    {
        UserProfile userProfile = null;
        try
        {
            userProfile = IOUtils.convertBytesToUserProfile(rs.getRecord(getRecordId(name)));
        }
        catch (RecordStoreNotOpenException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        catch (InvalidRecordIDException ex)
        {
            // Don't rethrow.
        }
        catch (RecordStoreException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        return userProfile;
    }

    /**
     * Saves the UserProfile.
     * @param userProfile the UserProfile
     * @return id
     */
    public int saveUserProfile(UserProfile userProfile)
    {
        int id = -1;
            
        try
        {
            byte[] data = IOUtils.convertUserProfileToBytes(userProfile);
            id = rs.addRecord(data, 0, data.length);
        }
        catch (RecordStoreNotOpenException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        catch (RecordStoreException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        return id;
    }

    /**
     * Deletes the UserProfile.
     * @param id the id
     */
    public void deleteUserProfile(String name)
    {
        try
        {
            rs.deleteRecord(getRecordId(name));
        }
        catch (RecordStoreNotOpenException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        catch (InvalidRecordIDException ex)
        {
            // Don't rethrow.
        }
        catch (RecordStoreException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
    }

    /**
     * Gets all the UserProfiles.
     * @return all the UserProfiles.
     */
    public UserProfile[] getUserProfiles()
    {
        UserProfile[] userProfiles = null;
        int i = 0;
        try
        {
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            
            if (re != null && re.hasNextElement()) {
            	userProfiles = new UserProfile[re.numRecords()];
                while (re.hasNextElement())
                {
                    UserProfile userProfile = IOUtils.convertBytesToUserProfile(re.nextRecord());
                    userProfiles[i++] = userProfile;
                }	
            } else {
            	userProfiles = new UserProfile[0];
            }
        }
        catch (InvalidRecordIDException ex)
        {
            // Don't rethrow.
        }
        catch (RecordStoreNotOpenException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        catch (RecordStoreException ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        }
        return userProfiles;
    }
    
	/**
	 * Gets record id based on user name
	 * @param name user name
	 * @return record id
	 */
	private int getRecordId(String name) {
		int result = -1;
		
		UserProfileFilter filter = new UserProfileFilter(name);
		try {
			RecordEnumeration re = rs.enumerateRecords(filter, null, false);
			
			while (re.hasNextElement()) {
				result = re.nextRecordId();
			}
		} catch (RecordStoreNotOpenException e) {
			e.printStackTrace();
		} catch (InvalidRecordIDException e) {
			e.printStackTrace();
		}
		
		return result;
	}

}
